﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OT.Data;
using OT.Areas.Admin.Models;
using PagedList;
namespace OT.Areas.Admin.Controllers
{
    public class QuestionController : Controller
    {
        #region Declaration
        readonly OTEntitiesme OTDb = new OTEntitiesme();
        int LanguageID = Utilities.GetLanguageID();
        #endregion

        #region Index
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(int pageNumber, int pageSize, string searchString, int pgindex)
        {
            List<Questions> Que = (from c in OTDb.Questions
                                   join sc in OTDb.Subjects
                                   on c.SubjectID equals sc.SubjectID into output
                                   from j in output.DefaultIfEmpty()
                                   join qt in OTDb.QuestionTypes
                                   on c.QuestionTypeID equals qt.QuestionTypeID
                                   join top in OTDb.Topics
                                  on c.TopicID equals top.TopicID
                                   join usr in OTDb.Users
                                   on c.UserID equals usr.UserID
                                   where c.LanguageID == LanguageID
                                   select new Questions
                                   {
                                       QuestionID = (int)c.QuestionID,
                                       QuestionName = c.QuestionName,
                                       QuestionType1 = qt.QuestionType1,
                                       SubjectName = j.SubjectName,
                                       FirstName = usr.FirstName,
                                       TopicName = top.TopicName,
                                       CreatedDate = (c.CreatedDate.HasValue) ? c.CreatedDate.Value : DateTime.MinValue,
                                       UpdatedDate = (c.UpdatedDate.HasValue) ? c.UpdatedDate.Value : DateTime.MinValue,

                                       Status = (bool)c.Status
                                   }).OrderBy(o => o.QuestionName).ToList<Questions>();
            if (!string.IsNullOrEmpty(searchString))
                Que = Que.Where(r => r.QuestionName.ToLower().Contains(searchString.ToLower())).ToList();
            int recount = Que.Count;
            Que = Que.Skip<Questions>(pgindex * (pageNumber - 1))
                .Take<Questions>(pgindex).ToList<Questions>();
            return Json(new
            {
                PageNumber = pageNumber,
                PageSize = pageSize,
                PgIndex = pgindex,
                Data = Que,
                RecordCount = recount
            });
        }
        #endregion

        #region Create
        public ActionResult Create()
        {
            Questions que = null;
            try
            {
                que = new Questions();
                var QT1 = OTDb.QuestionTypes.ToList();
                que.QuestionTypes = QT1;
                var Sub = OTDb.Subjects.Where(s=>s.Status==true).ToList();
                que.Subjects = Sub;
                var User = OTDb.Users.Where(u=>u.Status==true).ToList();
                que.Users = User;
                var top = OTDb.Topics.Where(t=>t.Status==true).ToList();
                que.Topics = top;
                var cat = OTDb.Categories.Where(c=>c.Status==true).ToList();
                que.catgo = cat;
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return PartialView(que);
        }

        [HttpPost]
        public string Create(String QuestionName, int QuestionTypeID, int TopicID, int SubjectID, string Answer1, string Answer2, string Answer3, string Answer4, byte DisplayAnswer, byte CorrectAnswer, Boolean UseLatex, Boolean Status)
        {
            string result = "";
            Question Q = null;
            int UserID = 0;
                if (Request.Cookies["AdminID"] != null)
                {
                    UserID = Convert.ToInt16(Request.Cookies["AdminID"].Value);
                }
                else
                {
                    TempData["notice"] = "Time Out ,Please Login";
                    Response.Redirect("~/Home");
                }
           
            try
            {
                if (ModelState.IsValid)
                {
                    Q = new Question();
                    Q.QuestionName = QuestionName;
                    Q.QuestionTypeID = QuestionTypeID;
                    Q.TopicID = TopicID;
                    Q.SubjectID = SubjectID;
                    Q.Answer1 = Answer1;
                    Q.Answer2 = Answer2;
                    Q.Answer3 = Answer3;
                    Q.Answer4 = Answer4;
                    Q.DisplayAnswer = DisplayAnswer;
                    Q.CorrectAnswer = CorrectAnswer;
                    Q.UseLatex = UseLatex;
                    Q.Status = Status;
                    Q.LanguageID = LanguageID;
                    Q.UserID = UserID;
                    Q.CreatedDate = DateTime.Now;
                    Q.UpdatedDate = DateTime.Now;
                    OTDb.Questions.Add(Q);
                    OTDb.SaveChanges();
                    result = "Sucess";
                }
                else
                {
                    var Citys = OTDb.Questions.ToList();
                    result = "NotValid";
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }
        #endregion

        #region Edit
        public ActionResult Edit(int QuestionID)
        {
            Questions que = null;
            int UserID = 0;
                if (Request.Cookies["AdminID"] != null)
                {
                    UserID = Convert.ToInt16(Request.Cookies["AdminID"].Value);
                }
                else
                {
                    TempData["notice"] = "Time Out ,Please Login";
                    Response.Redirect("~/Home");
                }
            try
            {
                var categry = OTDb.Questions.Where(r => r.QuestionID == QuestionID).SingleOrDefault();
                if (categry != null)
                {
                    que = new Questions();
                    que.QuestionName = categry.QuestionName;
                    que.CategoryID = GetCategory((int)categry.SubjectID);
                    que.QuestionTypeID = categry.QuestionTypeID;
                    que.TopicID = categry.TopicID;
                    que.SubjectID = categry.SubjectID;
                    que.Answer1 = categry.Answer1;
                    que.Answer2 = categry.Answer2;
                    que.Answer3 = categry.Answer3;
                    que.Answer4 = categry.Answer4;
                    que.UserID = (int)categry.UserID;
                    que.DisplayAnswer = (byte)categry.DisplayAnswer;
                    que.CorrectAnswer = (byte)categry.CorrectAnswer;
                    que.Status = (Boolean)categry.Status;
                    que.UseLatex = (Boolean)categry.UseLatex;
                    var QT1 = OTDb.QuestionTypes.ToList();
                    que.QuestionTypes = QT1;
                    var Sub = OTDb.Subjects.Where(p => p.SubjectID == categry.SubjectID).ToList();
                    que.Subjects = Sub;
                    var User = OTDb.Users.ToList();
                    que.Users = User;
                    var top = OTDb.Topics.Where(p => p.TopicID == categry.TopicID).ToList();
                    que.Topics = top;
                    var cat = OTDb.Categories.ToList();
                    que.catgo = cat;
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return PartialView(que);
        }

        [HttpPost]
        public string Edit(int QuestionID, String QuestionName, int QuestionTypeID, int TopicID, int SubjectID, string Answer1, string Answer2, string Answer3, string Answer4, byte DisplayAnswer, byte CorrectAnswer, Boolean UseLatex, Boolean Status)
        {
            int UserID = 0;
              if (Request.Cookies["AdminID"] != null)
                {
                    UserID = Convert.ToInt16(Request.Cookies["AdminID"].Value);
                }
                else
                {
                    TempData["notice"] = "Time Out ,Please Login";
                    Response.Redirect("~/Home");
                }
            string result = "";
            try
            {
                if (ModelState.IsValid)
                {
                    var que = OTDb.Questions.Where(r => r.QuestionID == QuestionID).SingleOrDefault();
                    if (que != null)
                    {
                        que.TopicID = TopicID;
                        que.QuestionID = QuestionID;
                        que.QuestionName = QuestionName;
                        que.QuestionTypeID = QuestionTypeID;
                        que.SubjectID = SubjectID;
                        que.Answer1 = Answer1;
                        que.Answer2 = Answer2;
                        que.Answer3 = Answer3;
                        que.Answer4 = Answer4;
                        que.DisplayAnswer = DisplayAnswer;
                        que.UserID = UserID;
                        que.Status = Status;
                        que.UseLatex = UseLatex;
                        que.CorrectAnswer = CorrectAnswer;
                        que.LanguageID = LanguageID;
                        que.UpdatedDate = DateTime.Now;
                        OTDb.SaveChanges();
                        result = "Sucess";
                    }
                }
                else
                {
                    result = "NotValid";
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }
        #endregion

        #region Delete
        public ActionResult Delete(int QuestionID)
        {
            Questions que = null;
            try
            {
                var categry = OTDb.Questions.Where(r => r.QuestionID == QuestionID).SingleOrDefault();
                if (categry != null)
                {
                    que = new Questions();
                    que.QuestionID = categry.QuestionID;
                    que.QuestionName = categry.QuestionName;
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return PartialView(que);
        }

        [HttpPost]
        public string Delete(int QuestionID, string IsDelete)
        {
            string result = "";
            try
            {
                var cat = OTDb.Questions.Where(r => r.QuestionID == QuestionID).SingleOrDefault();
                if (cat != null)
                {
                    OTDb.Questions.Remove(cat);
                    OTDb.SaveChanges();
                    result = "Success";
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }
        #endregion

        #region ExtraCall
        private IList<Subject> GetSub(int CategoryID)
        {
            return OTDb.Subjects.Where(m => m.CategoryID == CategoryID && m.Status==true).ToList();
        }

        private IList<Topic> GetTopic(int SubjectID)
        {
            return OTDb.Topics.Where(c => c.SubjectID == SubjectID && c.Status==true).ToList();
        }

        private int GetCategory(int CategoryID)
        {
            int rec;
            var query1 = (from c in OTDb.Subjects
                          orderby c.CategoryID ascending
                          where c.SubjectID == CategoryID
                          select c).SingleOrDefault();
            rec = (int)query1.CategoryID;
            return rec;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadSubject(string CategoryID)
        {
            var stateList = this.GetSub(Convert.ToInt32(CategoryID));
            var stateData = stateList.Select(m => new SelectListItem()
            {
                Text = m.SubjectName,
                Value = m.SubjectID.ToString(),
            });
            return Json(stateData, JsonRequestBehavior.AllowGet);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadTopic(string SubjectID)
        {
            var CityList = this.GetTopic(Convert.ToInt32(SubjectID));
            var CityData = CityList.Select(c => new SelectListItem()
            {
                Text = c.TopicName,
                Value = c.TopicID.ToString(),
            });
            return Json(CityData, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
